var repo = {};
repo.ctx = {};
repo.setCtx = function(ctx){
	repo.ctx = ctx;
};
repo.getCtx = function(){
	return repo.ctx;
};
repo.addLog=function(message,code){
	$.get(repo.getCtx()+"/report/log/addLog.jspx",{format:"json",m:message,c:code},function(data){
		
	});
};
repo.Category = {};
repo.Category.initGrid = function(){
	var options = {};
    var colNames = ["","序号","名称","编号","添加时间","添加人"];
    var colModel = [
        {name:"myac",fixed:true,width:80,formatter:"actions",formatoptions:{keys:true}},
        {name:"id",index:"id",width:10,key:true},
        {name:"name",index:"name",width:35,editable:true},
        {name:"code",index:"code",width:25,editable:true},
        {name:"addtime",index:"addtime",width:30},
        {name:"inputer",index:"inputer",width:25}
    ];
    options = {colNames:colNames,
               colModel:colModel,
               processUrl:"process.jspx?format=json",
               caption:"物料类别列表"};
    
    customGrid.init(options);
};

repo.Material={};
repo.Material.initGrid=function(){
	var options = {};
    var colNames = ["","序号","分类","编号","名称","型号","规格","芯数","颜色","单位"];
    var colModel = [
        {name:"myac",fixed:true,width:55,formatter:customActions,formatoptions:{
            keys:true,
            editformbutton:false,
            editUrl:"preEdit.jspx?id=",
            delUrl:"delete.jspx?id="}
        },
        {name:"id",index:"id",fixed:true,width:55,key:true},
        {name:"categoryName",index:"categoryId",width:20},
        {name:"code",index:"code",width:25},
        {name:"name",index:"name",width:30},
        {name:"model",index:"model",width:25},
        {name:"specification",index:"specification",width:35},
        {name:"wire",index:"wire",width:10},
        {name:"color",index:"color",width:15},
        {name:"unit",index:"unit",width:10}
    ];
    options={"colNames":colNames,
             "colModel":colModel,
             "newUrl":"preAdd.jspx",
             "caption":"物料管理"};
    
    customGrid.init(options);
};
repo.Material.getCategories = function(options){
	$.get(options.url,function(data){
		if(data!==undefined){
			var $container = $(options.container);
			if($container!==undefined){
				$container.empty();
				$container.append("<option value='0'>选择所有类别</option>");
				$.each(data.datarows,function(index,element){
					$container.append("<option value='"+element.id+"'>"+element.name+"</option>");
				});
			}
		}
	});
	
	$(options.container).on("change",function(){
		var value = $(this).val();
		var url = "getJson.jspx?format=json&category_id="+value;
		var options = {url:url};
		customGrid.reload(options);
	});
};
repo.Material.categories = function(options){
	$.get(options.url,function(data){
		if(data!==undefined){
			var $container = $(options.container);
			if($container!==undefined){
				$container.empty();
				$container.append("<option value='0'>选择所有类别</option>");
				$.each(data.datarows,function(index,element){
					$container.append("<option value='"+element.id+"'>"+element.name+"</option>");
				});
			}
			
			if(options.current_id!==undefined){
				$(options.container).val(options.current_id);
			}
		}
	});
	
};
repo.Material.fullnameEvent = function(){
    $("#model").on("change",function(){
		repo.Material.fullname();
	});
    
    $("#specification").on("change",function(){
    	repo.Material.fullname();
    });
};
repo.Material.fullname = function(){
	var model = $("#model").val(),
	    specification = $("#specification").val();
	$("#fullname").val(model+" "+specification);
};

repo.Stock = {};
repo.Stock.In = {};
repo.Stock.In.autocomplete = function(container){
	var ctx = repo.getCtx();
	$(container).autocomplete({
		serviceUrl:ctx+"/repo/material/listAutoModel.jspx?format=json&action=code",
		onSelect:function(suggestion){
			if(suggestion!==undefined){
				repo.Stock.In.getMaterial(suggestion.value);
			}
		}
	});
};
repo.Stock.In.getMaterial = function(code){
	var url = repo.getCtx() + "/repo/material/getOne.jspx";
	$.get(url,{format:"json",code:code},function(data){
		if(data!==undefined){
			var material = data.material;
			$("#material_name").html("").html(material.name);
			$("#material_model").html("").html(material.model);
			$("#material_specification").html("").html(material.specification);
			$("#material_color").html("").html(material.color);
			$("#span_material_unit").html("").html(material.unit);
			$("#material_unit").val(material.unit);
		}
	});
};
repo.Stock.In.initGrid = function(){
	var options = {};
    var colNames = ["","序号","编号","物料编号","物料名称","数量","单位","添加时间","添加人","状态"];
    var colModel = [
        {name:"myac",fixed:true,width:80,formatter:customActions,formatoptions:{keys:true}},
        {name:"id",index:"id",width:10,key:true},
        {name:"code",index:"code",width:35},
        {name:"materialCode",index:"materialCode",width:25},
        {name:"materialName",index:"materialName",width:35},
        {name:"totalNum",index:"totalNum",width:10},
        {name:"unit",index:"unit",width:8},
        {name:"addtime",index:"addtime",width:25},
        {name:"inputer",index:"inputer",width:25},
        {name:"checkstatus",index:"checkstatus",width:25}
    ];
    options = {colNames:colNames,
               colModel:colModel,
               processUrl:"process.jspx?format=json",
               caption:"物料入库列表"};
    
    customGrid.init(options);
};

repo.Stock.out={};
repo.Stock.out.initGrid = function(){
	var options = {};
    var colNames = ["序号","编号","物料编号","物料名称","物料型号","数量","单位","添加时间","添加人","操作"];
    var colModel = [
        {name:"id",index:"id",width:35,fixed:true,key:true},
        {name:"code",index:"code",width:20},
        {name:"materialCode",index:"materialCode",width:17},
        {name:"materialName",index:"materialName",width:25},
        {name:"model",index:"model",width:35},
        {name:"needNum",index:"needNum",width:10},
        {name:"finalUnit",index:"finalUnit",width:15},
        {name:"addtime",index:"addtime",width:25},
        {name:"inputer",index:"inputer",width:15},
        {name:"myac",width:25,align:"center",formatter:repo.Stock.out.customActions,formatoptions:{keys:true}},
    ];
    options = {colNames:colNames,
               colModel:colModel,
               processUrl:"process.jspx?format=json",
               caption:"物料出库列表"};
    
    customGrid.init(options);
};
repo.Stock.out.customActions = function(cellValue,options,rowObject){
	if(rowObject.flag===1){
		return "出库完成";
	}else if(rowObject.flag==2){
		return "内部半成品流动，无需确认";
	}else{
		return "<button class='btn btn-primary' onclick='repo.Stock.out.showConfirm("+options.rowId+")'>确认出库</button>";
	}
};
repo.Stock.out.showConfirm=function(id,ctx){
	if(id!==undefined && id>0){
		$.get("getOne.jspx?format=json",{id:id},function(data){
			if(data!==undefined && data.hasError===false){
				var template_data = template("confirm-template-materials-body",data);
				$("#stock_out_id").val(id);
				var $body = $("#confirm-materials-body").empty();
				$body.append(template_data);
				$("#show-stack-out-info-modal").modal();
			}
		});
	}
};
repo.Stock.out.confirm = function(ctx){
	var result = confirm("确认出库吗？");
	if(result){
		var id = $("#stock_out_id").val(),
		    memo = $("#stock_out_memo").val(),
		    finalNum=$("#stock_out_finalNum").val();
		$.get("confirm.jspx",{format:"json",id:id,memo:memo,finalNum:finalNum},function(data){
			if(data!==undefined && data.hasError===false){
				$("#show-stack-out-info-modal").modal('hide');
				var url = $("#gridTable").jqGrid('getGridParam','url');
				customGrid.reloadNoPage({url:url});
				if(data.stockOutCards!==undefined){
					$.each(data.stockOutCards,function(index,element){
						$.get(repo.getCtx()+"/product/product_task/changeStatus.jspx",{format:"json",id:element.taskId,status:"ReturnMaterial"},function(data){
							//console.debug(data);
						});
					});
				}
			}
		});
		repo.addLog(id+"号出库确认","006");
	}else{
		repo.addLog(id+"号出库确认取消","006");
	}
};

repo.StockReturn={};
repo.StockReturn.initGrid=function(){
	var options = {};
    var colNames = ["序号","编号","物料编号","数量","添加时间","添加人","操作"];
    var colModel = [
        {name:"id",index:"id",width:55,fixed:true,key:true},
        {name:"code",index:"code",width:35,editable:true},
        {name:"materialCode",index:"materialCode",width:25,editable:true},
        {name:"needNum",index:"needNum",width:30},
        {name:"addtime",index:"addtime",width:25},
        {name:"inputer",index:"inputer",width:25},
        {name:"myac",width:25,align:"center",formatter:repo.Stock.out.customActions,formatoptions:{keys:true}},
    ];
    options = {colNames:colNames,
               colModel:colModel,
               processUrl:"process.jspx?format=json",
               caption:"物料返库列表"};
    
    customGrid.init(options);
};

repo.Bom={};
repo.Bom.init=function(options){
	repo.Bom.initGrid();
	repo.Bom.autoCode(options);
};
repo.Bom.autoCode=function(options){
	$(options.container).autocomplete({
		serviceUrl:options.ctx+"/repo/material/listAutoModel.jspx?format=json&action=code",
		formatResult:function(suggestion,currentValue){
			return suggestion.value+" - "+suggestion.data;
		},
	    onSelect:function(suggestion){
		   var code = suggestion.value;
		   customGrid.reload({url:"getJson.jspx?format=json&code="+code});
	    }
	});
};
repo.Bom.initGrid=function(){
	var options = {}
    , colNames = ["","序号","编号","规格","物料编号","物料名称","规格","数量","描述","单位"]
    , colModel = [
		{name:"myac",fixed:true,width:55,formatter:customActions,formatoptions:{
		    keys:true,
		    editformbutton:false,
		    editUrl:"preEdit.jspx?id=",
		    canEdit:false,
		    delUrl:"delete.jspx?id="}
		},         
        {name:"id",index:"id",width:55,fixed:true,key:true},
        {name:"code",index:"code",width:15,editable:true},
        {name:"name",index:"model",width:20,editable:true},
        {name:"materialCode",index:"materialCode",width:15},
        {name:"materialName",index:"materialName",width:20},
        {name:"materialModel",index:"materialModel",width:25},
        {name:"needNum",index:"needNum",width:15},
		{name:"materialDesc",index:"materialDesc",width:15},
        {name:"unit",index:"unit",width:15}
    ];
    options = {colNames:colNames,
               colModel:colModel,
               newUrl:"preAdd.jspx",
               editUrl:"preEdit.jspx?id=",
               delUrl:"del.jspx?id=",
               canEdit:false,
               caption:"物料BOM列表"};
    
    customGrid.init(options);
};

repo.Bom.Edit={};
repo.Bom.Edit.init=function(options){
	var id=0;
	if(options!==undefined && options.isEdit){
		id = options.id;
	}
	$("#add_detail").on("click",function(){
		repo.Bom.Edit.addDetail(id,options.ctx);
	});
	
	repo.Bom.Edit.autoModel(".autocomplete",options.ctx);
	repo.Bom.Edit.autoMainMaterial("#code",options.ctx);
	repo.Bom.Edit.submit();
};
repo.Bom.Edit.autoMainMaterial=function(container,ctx){
	$(container).autocomplete({
		serviceUrl:ctx+"/repo/material/listAutoModel.jspx?action=code&format=json",
		formatResult:function(suggestion,currentValue){
			return suggestion.value+" - "+suggestion.data;
		},
	    onSelect:function(suggestion){
	    	var $detail_container = $("#detail_container");
	    	var code=suggestion.value;
	    	var $oldCode = $("#old_code"),
	    	oldCode=$oldCode.val();
	    	//console.debug($detail_container.children().length);
	    	//console.debug(oldCode+" "+code+" "+(oldCode!==code));
	    	if($detail_container.children().length>0){
	    		if(oldCode!==0 && oldCode!==code){
	    			var result = confirm("重新选择主物料信息，将清空物料详情，确定要重新选择吗？");
	    			if(result){
	    				$detail_container.empty();
	    				$("#current_index").val(0);
	    				$.get(ctx+"/repo/material/getOne.jspx",{format:"json",code:code},function(data){
	    					$("#name").val(data.material.model);
	    				});
	    				
	    				$.get(ctx+"/repo/bom/getList.jspx",{format:"json",code:code},function(data){
	    					repo.Bom.Edit.initData(ctx,data);
	    				});
	    				$oldCode.val(code);
	    			}else{
	    				$("#code").val(oldCode);
	    			}
	    		}
	    	}else{
	    		$.get(ctx+"/repo/material/getOne.jspx",{format:"json",code:code},function(data){
					$("#name").val(data.material.fullname);
				});
	    		
	    		$.get(ctx+"/repo/bom/getList.jspx",{format:"json",code:code},function(data){
					if(data!==undefined && data!==null){
						repo.Bom.Edit.initData(ctx,data);
					}
				});
	    		
	    		$oldCode.val(code);
	    	}
	    }
	});
};
repo.Bom.Edit.initData = function(ctx,data){
	if(data!==undefined && data.mainMaterial!==undefined){
		var material = data.mainMaterial;
		if(material!==null){
			var boms = material.materialBoms;
			if(boms!==null && boms.length>0){
				$.each(boms,function(index,bom){
					var extra={materialCode:bom.materialCode
							,materialName:bom.materialName
							,materialModel:bom.materialModel
							,materialDesc:bom.materialDesc
							,unit:bom.unit
							,needNum:bom.needNum
							,storeType:bom.storeType
							,id:bom.id
							,spec:bom.special
							,structure:bom.structure
							,thickness:bom.thickness
							,outerDiameter:bom.outerDiameter
							,boxNum:bom.boxNum};
					repo.Bom.Edit.addDetail(0,ctx,extra);
				});
			}
		}
	}
};
repo.Bom.Edit.autoModel=function(container,ctx){
	$(container).autocomplete({
		serviceUrl:ctx+"/repo/material/listAutoModel.jspx?action=code&format=json",
		width:300,
		formatResult:function(suggestion,currentValue){
			return suggestion.value+" - "+suggestion.data;
		},
	    onSelect:function(suggestion){
	    	var $parent = $(this).parent();
	    	if($parent!==undefined){
	    		var no=$parent.attr("data-no");
	    		 var code=suggestion.value;
		  		   $.get(ctx+"/repo/material/getOne.jspx",{format:"json",code:code},function(data){
		  			   if(data!==undefined && data!==null){
		  				   $("#materialName_"+no).val(data.material.name);
		  				   $("#materialModel_"+no).val(data.material.model+" "+data.material.specification);
		  				   $("#materialDesc_"+no).val(data.material.color);
		  				   $("#unit_"+no).val(data.material.unit);
		  			   }
		  		   });
	    	}
	    }
	});
};
repo.Bom.Edit.addDetail = function(id,ctx,extra){
	var $detailContainer = $("#detail_container"),
		$currentIndex = $("#current_index"),
		currentIndex=0;
	if($currentIndex!==undefined){
		try{
			currentIndex=parseInt($currentIndex.val());
		}catch(e){
			currentIndex = 0;
		}
	}
	if(currentIndex==0){
		currentIndex=1;
	}else{
		currentIndex=currentIndex+1;
	}
	$currentIndex.val(currentIndex);
	
	var options={};
	if(extra===undefined || extra===null){
		options = {index:currentIndex,id:id,storeType:'p',boxNum:0,needNum:0};
	}else{
		options = {index:currentIndex,id:extra.id,storeType:extra.storeType
				,boxNum:extra.boxNum
				,needNum:extra.needNum
				,materialCode:extra.materialCode
				,materialName:extra.materialName
				,materialModel:extra.materialModel
				,materialDesc:extra.materialDesc
				,spec:extra.spec
				,structure:extra.structure
				,thickness:extra.thickness
				,outerDiameter:extra.outerDiameter
				,unit:extra.unit};
	}
	var detailTemplate = template("bom_detail",options);
	$detailContainer.append(detailTemplate);
	repo.Bom.Edit.autoModel(".autocomplete",ctx);
	
	return false;
};
repo.Bom.Edit.delDetail = function(id){
	var result = confirm("确定要清除这条记录吗？");
	if(result){
		var content = $("#"+id);
		if(content!==undefined){
			content.remove();
		}
	}
	return false;
};
repo.Bom.Edit.submit=function(){
	
};

repo.InitData={};
repo.InitData.start=function(ctx){
	$('#data_type').on('change',function(){
		var value = $(this).val();
		if(0==value){
			$('#stock_file').css('display','');
			$('#bom_file').css('display','none');
			$('#material_file').css('display','none');
		}else if(1==value){
			$('#stock_file').css('display','none');
			$('#bom_file').css('display','none');
			$('#material_file').css('display','');
		}else{
			$('#stock_file').css('display','none');
			$('#bom_file').css('display','');
			$('#material_file').css('display','none');
		}
	});
	
	$("#start_button").on("click",function(){
		$('#row_count').val(0);
		var $importInfo = $('#import_info');
		$importInfo.html('开始解析Excel文件...').show();
		var dataType=$("#data_type").val(),
		filename=$("#linkurl").val();
		if(filename===undefined || filename===null){
			$importInfo.html('<span style="color:red">请先上传文件!</span>');
			return false;
		}
		if(0==dataType){
			$importInfo.html('<span style="color:green">开始解析库存数据！</span>');
		}else if(1==dataType){
			$importInfo.html('<span style="color:green">开始解析物料数据！</span>');
		}else{
			$importInfo.html('<span style="color:green">开始解析BOM数据！</span>');
		}
		var hasHeader = $('#has_header').val();
		$.post("initdata.jspx",{dataType:dataType,filename:filename,format:"json"},function(data){
			if(data===undefined || data===null){
				$importInfo.html('<span style="color:red">未能解析导数据！</span>');
			}
			else{
				$importInfo.html('<span style="color:green">成功获取数据！</span>');
			}
			if(0==dataType){//0.库存导入
				
				var $stock_init = $("#stock_init")
				,$stock_init_body=$("#stock_init_body");
				
				$stock_init.css('display','block');
				$('#material_init').css('display','none');
				$('#bom_init').css('display','none');
				
				if(data!==undefined && data.hasError===false){
					$importInfo.html('<span style="color:green">已成功获取库存数据，开始显示数据！</span>');
					$stock_init_body.empty();
					//console.log(data);
					var template_data = template("stock_init_template",data);
					//console.debug(template_data);
					$stock_init_body.append(template_data);
					$stock_init.css("display","");
					$("#import_flag").val(0);
					$importInfo.html('<span style="color:green">'+data.message+'</span>');
				}else{
					$importInfo.html('<span style="color:red">解析物料数据错误：'+data.message+'</span>');
				}
			}else if(1==dataType){ //1.物料导入
				$importInfo.html('<span style="color:green">已成功获取物料数据，开始显示数据！</span>');
				var $material_init_body=$('#material_init_body');
				$('#stock_init').css('display','none');
				$('#material_init').css('display','block');
				$('#bom_init').css('display','none');
				if(data!==undefined && data.hasError===false){
					$importInfo.html('<span style="color:green">已成功获取物料数据，开始显示数据！</span>');
					$material_init_body.empty();
	
					var template_data = template("material_init_template",data);
					//console.debug(template_data);
					$material_init_body.append(template_data);
					$("#import_flag").val(0);
					
					$('#row_count').val(data.count);
					var errorMessage = "";
					if(data.errorCount>0){
						errorMessage= " <span style='color:red'>有"+data.errorCount+"条数据不符合导入条件，请检查！</span>";
					}
					$importInfo.html('<span style="color:green">'+data.message+'</span>'+errorMessage);
				}else{
					$importInfo.html('<span style="color:red">解析物料数据错误：'+data.message+'</span>');
				}
			}else{//2.bom导入
				
				var $bom_init = $("#bom_init")
				,$bom_init_body=$("#bom_init_body");
				
				$('#stock_init').css('display','none');
				$('#material_init').css('display','none');
				$('#bom_init').css('display','block');
				
				$('#import_flag').val(0);
				if(data!==undefined && data.hasError===false){
					$importInfo.html('<span style="color:green">已成功获取BOM数据，开始显示数据！</span>');
					$bom_init_body.empty();
					//console.log(data);
					var template_data = template("bom_init_template",data);
					//console.debug(template_data);
					$bom_init_body.append(template_data);
					$("#import_flag").val(0);
					
					$('#row_count').val(data.count);
					var errorMessage = "";
					if(data.errorCount>0){
						errorMessage= " <span style='color:red'>有"+data.errorCount+"条数据不符和导入条件，请检查！</span>";
					}
					if(data.hasFile!==undefined && data.hasFile===true){
						errorMessage += "<a href='download.jspx?format=json&filename="+data.filename+"&sheetname="+data.name+"'>下载错误信息</a>";
					}
					$importInfo.html('<span style="color:green">'+data.message+'</span>'+errorMessage);
				}else{
					$importInfo.html('<span style="color:red">解析BOM数据错误：'+data.message+'</span>');
				}
			}//end bom
		});
	});
};
repo.InitData.import=function(){
	$("#import_button").on("click",function(){
		var import_flag = $("#import_flag").val();
		if(import_flag===1){
			alert("已经标记为导入，不能再导入了！");
			return false;
		}
		var row_count = $('#row_count').val();
		if(row_count===0){
			alert('无数据，无需导入！');
			return false;
		}
		$('#import_info').html('开始导入数据！').show();
		var dataType = $('#data_type').val(),
		    importType = $('input:radio[name=import_type]:checked').val(),
		    hasHeader = $('input[name=has_header]:checked').val();
		    if(hasHeader===undefined){
		    	hasHeader=0;
		    }
		    
		    filename=$("#linkurl").val();
			if(filename===undefined || filename===null){
				$importInfo.html('<span style="color:red">请先上传文件!</span>');
				return false;
			}
			
			var requestData =  "dataType="+dataType+"&importType="+importType+"&hasHeader="+hasHeader+"&rowCount="+row_count+"&filename="+filename;
		$.post("import.jspx?format=json",requestData,function(data){
			if(data!==undefined && data.hasError===false){
				$("#import_flag").val(1);
				$('#import_info').html(data.message);
				$('#import_info').css('color','green');
			}else{
				$('#import_info').html(data.message);
				$('#import_info').css('color','red');
			}
		});
	});
};